#!/usr/bin/env python
# -*- coding:utf-8 -*-
# @Time    : 2024/6/5 7:55
# @Author  : jiangwei
# @Site    : 
# @File    : login_dewu.py
# @Software: PyCharm
import sys
import os

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.append(BASE_DIR)



import time
import socket
import logging
from pathlib import Path
from filelock import FileLock, Timeout
from tempfile import gettempdir, TemporaryDirectory
from DrissionPage import ChromiumPage
from pipeline.redis_connect import save_key_redis

logging.getLogger("urllib3.connectionpool").setLevel(logging.ERROR)


# if platform.system() != 'Windows':
#     WEBDRIVER_PATH = f'/opt/google/chrome'
#     print(WEBDRIVER_PATH)
#     set_paths(browser_path=WEBDRIVER_PATH)
# else:
#     set_paths(browser_path='C:\Program Files (x86)\Google\Chrome\Application\chrome.exe')
# 创建默认的窗口对象


def find_free_port():
    """找到一个可用的端口，用于浏览器开启远程调试端口，防止端口冲突"""
    with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
        s.bind(('127.0.0.1', 0))
        return s.getsockname()[1]


# def is_port_available(port=9223, check_scope=100) -> int:
#     """
#     检查端口是否占用，并返回一个未被占用的端口
#     :param port: 默认起始端口
#     :param check_scope: 端口检查范围
#     :return: port
#     """
#     # with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
#     #     for pt in range(port, port + check_scope):
#     #         if s.connect_ex(('127.0.0.1', pt)) != 0:
#     #             return pt
#     # ports = [54212, 64655, 57881, 53006, 50125, 61859, 58311, 53203, 59204, 49424, 49334, 55919, 55511, 54212, 56618, 51598]
#     # with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
#     #     for pt in ports:
#     #         if s.connect_ex(('127.0.0.1', pt)) != 0:
#     #             return pt
#     return 63855


def is_port_available(port=49424, check_scope=100) -> int:
    """
    检查端口是否占用，并返回一个未被占用的端口
    :param port: 默认起始端口
    :param check_scope: 端口检查范围
    :return: port
    """
    with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
        for pt in range(port, port + check_scope):
            lock_dir = Path(gettempdir()) / 'is_port_available'
            lock_dir.mkdir(parents=True, exist_ok=True)
            lock_path = lock_dir / f'port_{pt}.lock'
            # 如果文件不存在，创建文件
            if not lock_path.exists():
                lock_path.touch()

            lock = FileLock(lock_path, timeout=0)
            try:
                with lock:
                    if s.connect_ex(('127.0.0.1', pt)) != 0:
                        return pt
            except Timeout:
                continue


def login_dewu_driss():
    """
    登录得物
    """
    free_port = find_free_port()
    addr_driver_opts = "127.0.0.1:{}".format(free_port)
    print(addr_driver_opts)
    page = ChromiumPage(addr_driver_opts=addr_driver_opts)

    try:
        # 账号：15102742537:13631337802
        # 密码：Miniso123
        page.get('https://stark.dewu.com/')
        user = "15102742537:13631337802"
        pwd = "Miniso123"
        time.sleep(6)
        # login_container = page.eles("xpath://div[@class='header_wrap___hh9Vs header_wrap_fixed___b6mG9 header_wrap_transparent___ITJuQ']//div[@class='login_container___FWpwg']")
        notice_img = page.eles("xpath://img[@class='settle_modal_close']")
        # print(notice_img)
        if notice_img:
            notice_img[0].click()
            print("关闭入驻提示框")


        # login_container[0].click()
        # time.sleep(3)
        # print("切换登录框页面")

        # 2025.8.25加多"去登录按钮"
        time.sleep(5)
        go_login=page.ele("xpath://button[@class='el-tooltip el-button el-button--text el-button--medium']")
        if go_login:
            go_login.click()
            print("点击去登录")

        # 2025.9.26加多“密码登录按钮”
        login_by_pwd=page.ele("#tab-password")
        if login_by_pwd:
            login_by_pwd.click()
            print("点击密码登录")
            time.sleep(2)



        # 1 输入账号
        page.eles("xpath://input[@autocomplete='new-password']")[0].clear()
        time.sleep(1)
        page.eles("xpath://input[@autocomplete='new-password']")[0].input(user)
        time.sleep(3)
        print("【输入账号：{}】成功".format(user))

        # 2 输入密码
        page.eles("xpath://input[@class='el-input__inner']")[-1].clear()
        time.sleep(1)
        page.eles("xpath://input[@class='el-input__inner']")[-1].input(pwd)
        time.sleep(3)
        print("【输入密码:{}】成功".format(pwd))

        # 3 点同意
        agree_ele = page.eles("xpath://label[@class='el-checkbox el-tooltip']//span[@class='el-checkbox__inner']")
        agree_ele[0].click()

        # 4 点击登录
        button_ele = page.eles("xpath://button[@class='el-tooltip el-button el-button--primary el-button--large']")
        button_ele[0].click()
        print("【点击登录】成功")
        time.sleep(15)

        url_now = page.url
        print("----", url_now)
        main_page_ele = page.eles("#pcHeaderRightInfo")
        login_u = page.eles("xpath://input[@autocomplete='new-password']")
        print("主页元素：{}".format(main_page_ele))
        if main_page_ele or len(login_u) == 0:
            print("登录成功，获取cookie")
            cookies = ""
            cookie = page.cookies
            # print(cookie)
            for k, v in cookie.items():
                str_cookie = '{}={}'.format(k, v) + ";"
                cookies += str_cookie
            print(cookies)
            # 将cookie存到redis
            save_key_redis(name="dewu", key="dewu_api", cookie=cookies)


        else:
            print("请开发排查页面情况，是否出现滑块等")
            page.get_screenshot("login_dewu_slider.png")

    except Exception as e:
        page.get_screenshot("login_dewu_driss_error.png")
        print(e)

    finally:
        page.close_tabs()


if __name__ == '__main__':
    login_dewu_driss()
